/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package simplepushclient;

import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.*;
import javax.swing.*;


/**
 * @author Filip
 */
public class PusherTray{
    private final static String AVAILABLE_COMMANDS = " Available commands are:"
            + "\nspotify:[spotify-uri] - opens Spotify correctly"
            + "\nplay:[filename] searches and plays a tune using Winamp"
            + "\nenqueue:[filename] searches and enqueues a tune using Winamp"
            + "\nvolume:[percent] sets systemvolume"
            + "\ngoogle:[text] open browser and searches on [text]"
            + "\nopen:[link] tries to download and play file [BETA]"
            + "\nkill:[processname] e.g. explorer.exe"
            + "\npress:[keystroke] follows NirCmd Syntax e.g ctrl+w"
            + "\nspeak:[text] speaks text"
            + "\nballoon:[text] tray-balloon"
            + "\ncmd:[command] cmd-exec"
            + "\nnircmd:[NirCmd-command] e.g. monitor on"
            + "\nserver:[servercommand] e.g. kill"
            + "\nyoutube:[command] e.g. fullscreen"
            + "\nmessage:[text] show a messagepane"
            + "\nip:[text] starts monitor, speak:[remote ip] [text] , message:[remote ip] [text] "
            + "\n[link] - plain url-link e.g. http://www.google.com/ "
            + "\n       - youtube.com-movie [link] e.g. http://www.youtube.com/watch?v=h5aSa4tmVNM"
            + "\n       - soundcloud.com-tune [link] e.g. http://soundcloud.com/rjchevalier/rj...ing";

    private Int savedVolume;
    private History history;
    private String[] ip;
    private Sender s;
    private Image icon;
    private TrayIcon trayIcon;
    private JIntellitype jintellitype;
    private SystemTray tray;
    private PopupMenu popup;
    private URL iconurl;

    private ActionListener historyListener;
    private ActionListener pushClipboardListener;
    private ActionListener pushListener;
    private ActionListener exitListener;
    private ActionListener changeIpListener;
    private ActionListener mediaControllerItemListener;
    private ActionListener chromeControllerItemListener;
    private ActionListener windowControllerItemListener;
    private ActionListener showCommandsListener;

    public PusherTray(String[] ip) {
        this.savedVolume = new Int(0);
        this.history = new History();
        this.ip = ip;
        this.icon = null;
        this.s = new Sender(ip);
    }
    
    public void createTray(){
        tray = SystemTray.getSystemTray();
        popup = new PopupMenu("Pusher");
        try {
            iconurl = new URL("http://img529.imageshack.us/img529/6775/33212910.gif");
            icon = Toolkit.getDefaultToolkit().getImage(iconurl);
        }catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
        trayIcon = new TrayIcon(icon,"Pusher (Client)", popup);
        trayIcon.setImageAutoSize(true);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            MenuItem sendItem = new MenuItem("Push custom(Crtl+Shift+P)");
            MenuItem sendClipItem = new MenuItem("Push clipboard (Ctrl+Shift+V)");
            MenuItem historyItem = new MenuItem("View history");
            MenuItem commandsItem = new MenuItem("View available commands");
            MenuItem mediaController = new MenuItem("Mediacontrol");
            MenuItem chromeController = new MenuItem("Chromecontrol");
            MenuItem windowController = new MenuItem("Windowcontrol");
            MenuItem changeAdress = new MenuItem("Set serveradress");
            MenuItem exitItem = new MenuItem("Exit");

            createListeners();

            sendItem.addActionListener(pushListener);
            sendClipItem.addActionListener(pushClipboardListener);
            historyItem.addActionListener(historyListener);
            commandsItem.addActionListener(showCommandsListener);
            mediaController.addActionListener(mediaControllerItemListener);
            chromeController.addActionListener(chromeControllerItemListener);
            windowController.addActionListener(windowControllerItemListener);
            changeAdress.addActionListener(changeIpListener);
            exitItem.addActionListener(exitListener);

            popup.add(sendItem);
            popup.add(sendClipItem);
            popup.addSeparator();
            popup.add(mediaController);
            popup.add(chromeController);
            popup.add(windowController);
            popup.addSeparator();
            popup.add(historyItem);
            popup.add(commandsItem);
            popup.add(changeAdress);
            popup.addSeparator();
            popup.add(exitItem);

            tray.add(trayIcon);
        }catch (Exception e) {
            p(e.toString());
            e.printStackTrace();
            e.getCause().printStackTrace();
        }
      }

    public void promtServerAdress(){
        String tmp = JOptionPane.showInputDialog("ip:port",ip[0]+":"+ip[1]);
        if(!(tmp==null || tmp.isEmpty())){
            ip= tmp.split(":");
            s = new Sender(ip);
            try {
                Client.saveAdress(tmp);
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void send(String data){
        s.setData(data);
        s.run();
    }

    public static boolean sendPing(){
        return true;
    }
    public String[] getIp() {
        return ip;
    }

    public PusherTray getInstance(){
        return this;
    }

    public History getHistory() {
        return history;
    }
    
    public Image getImage() {
        return icon;
    }
    private static void p(String toString) {
        JOptionPane.showMessageDialog(null, toString);
    }

    public Int getSavedVolume() {
        return savedVolume;
    }

    public void createListeners(){
        showCommandsListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,AVAILABLE_COMMANDS);
            }
        };

        historyListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                HistorySend qs = new HistorySend(getInstance());
                qs.setVisible(true);
            }
        };
        pushListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String data="";
                if(!history.getLatest().isEmpty())
                    data = JOptionPane.showInputDialog("URL to send\ndefault: latest push content)", history.getLatest());
                else{
                    data = JOptionPane.showInputDialog("URL to send", "speak: ");
                }
                send(data);
                history.add(data);
            }
        };
        pushClipboardListener = new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                sendClipboard();
            }
        };
        mediaControllerItemListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MediaControl mc = new MediaControl(getInstance());
                mc.setVisible(true);
            }
        };

        chromeControllerItemListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ChromeController cc = new ChromeController(getInstance());
                cc.setVisible(true);
            }
        };

        windowControllerItemListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                WindowController wc = new WindowController(getInstance());
                wc.setVisible(true);
            }
        };

        changeIpListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                promtServerAdress();
            }
        };
        exitListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                history.saveHistory();
                try {
                    JIntellitype j = JIntellitype.getInstance();
                    j.unregisterHotKey(1);
                    j.unregisterHotKey(2);
                    j.unregisterHotKey(3);
                    j.unregisterHotKey(4);
                    j.unregisterHotKey(5);
                    j.unregisterHotKey(6);
                    j.unregisterHotKey(7);
                    j.unregisterHotKey(8);
                    j.cleanUp();
                }catch (Exception ex){ex.printStackTrace();}
                System.exit(0);
            }
        };
        jintellitype = startIntelliType();
        if(jintellitype!=null){
            jintellitype.registerHotKey(1, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, 0x56);//Send clipboard
            jintellitype.registerHotKey(2, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, 0x27);//Right
            jintellitype.registerHotKey(2, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, JIntellitype.APPCOMMAND_MEDIA_NEXTTRACK);//nextmedia
            jintellitype.registerHotKey(3, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, 0x25);//Left
            jintellitype.registerHotKey(3, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, JIntellitype.APPCOMMAND_MEDIA_PREVIOUSTRACK);//prevmedia
            jintellitype.registerHotKey(4, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, 0x28);//Down
            jintellitype.registerHotKey(4, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, JIntellitype.APPCOMMAND_MEDIA_PLAY_PAUSE);//playpausmedia
            jintellitype.registerHotKey(5, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, 0x26);//Up
            jintellitype.registerHotKey(5, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, JIntellitype.APPCOMMAND_MEDIA_STOP);//stopvmedia
            jintellitype.registerHotKey(6, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, 0x21);//PageUP
            jintellitype.registerHotKey(7, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, 0x22);//PageDown
            jintellitype.registerHotKey(8, JIntellitype.MOD_CONTROL+JIntellitype.MOD_SHIFT, 0x50);//Send custom

            HotkeyListener h = new HotkeyListener(){
                public void onHotKey(int i) {
                    switch(i) {
                        case 1:
                            sendClipboard();
                            break;
                        case 2:
                            send("nircmd:sendkeypress 0xB0"); //Next
                            break;
                        case 3:
                            send("nircmd:sendkeypress 0xB1"); //Prev
                            break;
                        case 4:
                            send("nircmd:sendkeypress 0xB3");//Play
                            break;
                        case 5:
                            send("nircmd:sendkeypress 0xB2");//Stop
                            break;
                        case 6:
                            send("nircmd:changesysvolume 5000");
                            break;
                        case 7:
                            send("nircmd:changesysvolume -5000");
                            break;
                        case 8:
                            pushListener.actionPerformed(null);
                        default:
                    }
                }
            };
            jintellitype.addHotKeyListener(h);
        }
    }

    private JIntellitype startIntelliType() {
        File intelliDLL = new File(System.getenv("windir"), "JIntellitype.dll");
        File intelliDLL64 = new File(System.getenv("windir"), "JIntellitype64.dll");
        JIntellitype j = null;
        try {
            JIntellitype.setLibraryLocation(intelliDLL64.getAbsolutePath());
            j = JIntellitype.getInstance();
        } catch (Exception e) {
            System.out.println("Couldn't load from: " + intelliDLL64.getAbsolutePath());
            e.printStackTrace();
            j = null;
            try {
                JIntellitype.setLibraryLocation(intelliDLL.getAbsolutePath());
                j = JIntellitype.getInstance();
            } catch (Exception ex) {
                System.out.println("Couldn't load from: " + intelliDLL.getAbsolutePath());
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "Please install JIntellitype.dll (into %WinDir%)\n" + intelliDLL.getAbsolutePath() + "\nor\n" + intelliDLL64.getAbsolutePath());
            }
        }
        return j;
    }
    
    private void sendClipboard() {
        String clipboard = Helper.getClipboardContents();
        if (!(clipboard == null || clipboard.isEmpty())) {
            send(clipboard);
            history.add(clipboard);
        } else {
            trayIcon.displayMessage("Pusher", "Clipboard was empty!", TrayIcon.MessageType.ERROR);
        }
    }

    public JIntellitype getJintellitype() {
        return jintellitype;
    }
    
}